﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using SY.BasicData.Api.Read.Applications.Basic.Command;
using SY.BasicData.Api.Read.Dto;
using SY.BasicData.Domain.Base;
using SY.BasicData.Domain.Basic;
using SY.BasicData.Domain.Cultivation;
using SY.BasicData.Domain.DeepProcessing;
using SY.BasicData.Domain.SlaughterInformation;
using SY.BasicData.ErrorCode;
using SY.BasicData.Infrastructures;


namespace SY.BasicData.Api.Read.Applications.Basic.CommandHandler
{
    public class GetManagementCommandHandler : IRequestHandler<GetManagementCommand, ApiResult<ApiPaging<BasicDto>>>
    {
        private readonly IBaseRepository<BasicModel> basicRepository;
        private readonly IBaseRepository<StoreModel> storeRepository;
        private readonly IBaseRepository<CultivationModel> cultivalRepository;
        private readonly IBaseRepository<SlaughterModel> slaughterRepository;
        private readonly IBaseRepository<DeepProcessingModel> deepprocessRepository;
        private readonly ILogger<GetManagementCommandHandler> logger;

        public GetManagementCommandHandler(IBaseRepository<BasicModel> basicRepository, IBaseRepository<StoreModel> storeRepository, ILogger<GetManagementCommandHandler> logger, IBaseRepository<CultivationModel> cultivalRepository, IBaseRepository<SlaughterModel> slaughterRepository, IBaseRepository<DeepProcessingModel> deepprocessRepository)
        {
            this.basicRepository = basicRepository;
            this.storeRepository = storeRepository;
            this.logger = logger;
            this.cultivalRepository = cultivalRepository;
            this.slaughterRepository = slaughterRepository;
            this.deepprocessRepository = deepprocessRepository;
        }

        public async Task<ApiResult<ApiPaging<BasicDto>>> Handle(GetManagementCommand request, CancellationToken cancellationToken)
        {
            logger.LogInformation("商品信息列表展示成功");
            ApiResult<ApiPaging<BasicDto>> result = new ApiResult<ApiPaging<BasicDto>>();
            result.Code = ApiEnum.Success;
            var basics = basicRepository.GetAll().Where(c => !c.IsDeleted);
            var stores = storeRepository.GetAll().Where(c => !c.IsDeleted);
            var breedings = cultivalRepository.GetAll().Where(c => !c.IsDeleted);
            var Slaughter = slaughterRepository.GetAll().Where(c => !c.IsDeleted);
            var Processing = deepprocessRepository.GetAll().Where(c => !c.IsDeleted);
            result.Message = "商品信息列表展示成功";

            var list = from a in basicRepository.GetAll()
                       join b in storeRepository.GetAll() on a.Sid equals b.Id
                       let hasBreeding = breedings.Any(b => b.Batch == a.Batch)
                       let hasSlaughter = Slaughter.Any(s => s.Batch == a.Batch)
                       let hasProcessing = Processing.Any(p => p.Batch == a.Batch)
                       where a.IsDeleted == false
                       select new BasicDto
                       {
                           Id = a.Id,
                           Sid = a.Sid,
                           Batch = a.Batch,
                           Expiration = a.Expiration,
                           License = a.License,
                           Company = a.Company,
                           Picture = a.Picture,
                           Completeness = CalculateCompleteness(hasBreeding, hasSlaughter, hasProcessing),
                           Creator = a.Creator,
                           CreatorDate = a.CreatorDate,
                           Updator = a.Updator,
                           UpdatorDate = a.UpdatorDate,
                           StoreName = b.StoreName,

                       };

            var TotalCount = list.Count();
            var TotalPage = (int)Math.Ceiling(TotalCount * 1.0 / request.PageSize);
            list = list.OrderByDescending(x => x.Sid).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            ApiPaging<BasicDto> apiPaging = new ApiPaging<BasicDto>();
            apiPaging.TotalCount = TotalCount;
            apiPaging.TotalPage = TotalPage;
            apiPaging.data = list.ToList();
            result.Data = apiPaging;



            foreach (var item in apiPaging.data)
            {
                var basic = await basicRepository.GetAll().FirstOrDefaultAsync(b => b.Batch == item.Batch && !b.IsDeleted);
                if (basic != null)
                {
                    basic.Completeness = item.Completeness;
                    await basicRepository.Update(basic);
                }



            }
            return await Task.FromResult(result);




        }
        private static int CalculateCompleteness(bool hasBreeding, bool hasSlaughter, bool hasProcessing)
        {
            int completeness = 10;
            if (hasBreeding) completeness += 30;
            if (hasSlaughter) completeness += 30;
            if (hasProcessing) completeness += 30;
            return completeness;
        }
    }
}
